package com.arvinclub.web.controller.blog;

import com.arvinclub.model.entity.Blog;
import com.arvinclub.model.entity.Comment;
import com.arvinclub.model.entity.User;
import com.arvinclub.model.util.ToolsUtil;
import com.arvinclub.service.service.CommentService;
import com.arvinclub.service.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 评论相关
 */
@Controller
public class CommentController {

    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;

    /**
     * 发布评论
     *
     * @return 成功则转到微博详情，否则转到错误提示页面
     */
    @PostMapping("user/addComment/{blogId}")
    public String addComment(Comment comment, HttpSession httpSession, @PathVariable int blogId) {
        if (StringUtils.isNotBlank(comment.getContent())) {
            /*构建评论*/
            User me = (User) httpSession.getAttribute("user");
            userService.checkMuted(me);
            comment.setUser(me);
            comment.setTime(ToolsUtil.getNowTimeString());
            Blog blog = new Blog();
            blog.setId(blogId);
            comment.setBlog(blog);
            commentService.addComment(comment);
        }
        /*添加评论*/
        return "redirect:/user/detail.html/" + blogId;
    }

    /**
     * 删除评论
     *
     * @return 成功则转到微博详情，否则转到错误提示页面
     */
    @GetMapping("user/delComment/{commentId}")
    public String delComment(HttpSession httpSession, @PathVariable int commentId) {
        Comment comment = commentService.backCommentById(commentId);
        User me = (User) httpSession.getAttribute("user");
        User someone = comment.getUser();
        User blogger = comment.getBlog().getUser();
        if (me.equals(someone) || me.getAdmin() > someone.getAdmin() ||
                me.equals(blogger) || me.getAdmin() > blogger.getAdmin()) {

            commentService.delComment(commentId);
        }
        return "redirect:/user/detail.html/" + comment.getBlog().getId();
    }

    /**
     * 编辑评论
     *
     * @return 成功则转到微博详情，否则转到错误提示页面
     */
    @PostMapping("user/editComment")
    public String editComment(Comment comment, HttpSession httpSession) {
        Comment oldComment = commentService.backCommentById(comment.getId());
        User me = (User) httpSession.getAttribute("user");
        userService.checkMuted(me);
        if (StringUtils.isNotEmpty(comment.getContent()) && me.equals(oldComment.getUser())) {
            commentService.updateComment(comment);
        }
        return "redirect:/user/detail.html/" + oldComment.getBlog().getId();
    }
}
